<!--
 * Copyright © 2025 上海火金网络科技有限公司. All rights reserved.
 * Protocol Validations Simple Editor - 协议Validations简单编辑器
 *
 * 功能：参考add-or-edit简单表格UI，编辑功能使用弹窗，确保保存生效
 * 版本：1.0.0
 *
 * Website: https://www.anypay.com
-->

<template>
  <div class="protocol-validations-simple-editor">
    <!-- 头部工具栏 -->
    <div class="editor-header">
      <div class="header-left">
        <h2>
          <SafetyCertificateOutlined />
          协议验证规则编辑器
        </h2>
        <div class="protocol-info" v-if="protocol">
          <a-tag color="blue">{{ protocol.name }}</a-tag>
          <span class="field-count">共 {{ totalFieldsCount }} 个字段</span>
        </div>
      </div>
      <div class="header-actions">
        <a-space>
          <a-button type="primary" @click="handleSave" :loading="saving">
            <SaveOutlined />
            保存验证规则
          </a-button>
        </a-space>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="editor-content">
      <!-- 协议加载状态 -->
      <div v-if="loading" class="loading-state">
        <a-skeleton active :paragraph="{ rows: 6 }" />
      </div>

      <!-- 无协议状态 -->
      <div v-else-if="!protocol" class="empty-state">
        <a-empty description="请加载协议数据" />
      </div>

      <!-- 配置段列表 -->
      <div v-else class="sections-container">
        <a-card
          v-for="(section, sectionIndex) in protocol.configSections"
          :key="section.sectionKey"
          size="small"
          class="section-card"
        >
          <template #title>
            <div class="section-title">
              <span>{{ section.sectionName }}</span>
              <a-tag size="small" color="blue">{{ section.fields?.length || 0 }} 个字段</a-tag>
            </div>
          </template>

          <!-- 字段表格 - 参考add-or-edit简单样式 -->
          <div class="fields-list">
            <div
              v-for="(field, fieldIndex) in section.fields"
              :key="`${section.sectionKey}-field-${fieldIndex}`"
              class="field-item"
            >
              <a-row :gutter="8">
                <!-- 字段ID -->
                <a-col :span="4">
                  <code class="field-key">{{ field.fieldKey }}</code>
                </a-col>

                <!-- 字段名称 -->
                <a-col :span="4">
                  <strong>{{ field.fieldName }}</strong>
                </a-col>

                <!-- 字段类型 -->
                <a-col :span="3">
                  <a-tag size="small" :color="getFieldTypeColor(field.fieldType)">
                    {{ getFieldTypeShortName(field.fieldType) }}
                  </a-tag>
                </a-col>

                <!-- 必填状态 -->
                <a-col :span="2">
                  <a-tag v-if="field.required" color="red" size="small">必填</a-tag>
                  <span v-else>-</span>
                </a-col>

                <!-- 验证状态 -->
                <a-col :span="4">
                  <a-tag v-if="hasValidationRules(field)" color="green" size="small">
                    {{ getValidationRulesCount(field) }}个规则
                  </a-tag>
                  <span v-else>无验证</span>
                </a-col>

                <!-- 操作列 -->
                <a-col :span="7">
                  <a-space size="small">
                    <a-button
                      type="link"
                      size="small"
                      @click="viewFieldValidation(field)"
                      :disabled="!hasValidationRules(field)"
                    >
                      <EyeOutlined />查看
                    </a-button>
                    <a-button
                      type="link"
                      size="small"
                      @click="editFieldValidation(field, sectionIndex, fieldIndex)"
                    >
                      <EditOutlined />编辑
                    </a-button>
                    <a-button
                      type="link"
                      size="small"
                      danger
                      @click="clearFieldValidation(sectionIndex, fieldIndex)"
                      :disabled="!hasValidationRules(field)"
                    >
                      <DeleteOutlined />清除
                    </a-button>
                  </a-space>
                </a-col>
              </a-row>
            </div>
          </div>
        </a-card>
      </div>
    </div>

    <!-- 验证规则查看弹窗 -->
    <a-modal
      v-model:open="showViewModal"
      title="验证规则详情"
      :footer="null"
      width="600px"
    >
      <div v-if="viewingField" class="validation-details">
        <div class="field-basic-info">
          <h3>{{ viewingField.fieldName }} ({{ viewingField.fieldKey }})</h3>
          <a-tag :color="getFieldTypeColor(viewingField.fieldType)">
            {{ viewingField.fieldType }}
          </a-tag>
          <a-tag v-if="viewingField.required" color="red" size="small">必填字段</a-tag>
        </div>

        <a-divider />

        <div class="validation-rules-list">
          <div v-if="viewingField.validation?.required" class="validation-rule">
            <a-tag color="red" size="small">必填验证</a-tag>
            <span>: 该字段为必填项</span>
          </div>
          <div v-if="viewingField.validation?.minLength" class="validation-rule">
            <a-tag color="blue" size="small">最小长度</a-tag>
            <span>: {{ viewingField.validation.minLength }} 字符</span>
          </div>
          <div v-if="viewingField.validation?.maxLength" class="validation-rule">
            <a-tag color="blue" size="small">最大长度</a-tag>
            <span>: {{ viewingField.validation.maxLength }} 字符</span>
          </div>
          <div v-if="viewingField.validation?.min !== undefined" class="validation-rule">
            <a-tag color="purple" size="small">最小值</a-tag>
            <span>: {{ viewingField.validation.min }}</span>
          </div>
          <div v-if="viewingField.validation?.max !== undefined" class="validation-rule">
            <a-tag color="purple" size="small">最大值</a-tag>
            <span>: {{ viewingField.validation.max }}</span>
          </div>
          <div v-if="viewingField.validation?.pattern" class="validation-rule">
            <a-tag color="orange" size="small">正则表达式</a-tag>
            <span>: <code>{{ viewingField.validation.pattern }}</code></span>
          </div>
          <div v-if="viewingField.validation?.message" class="validation-rule">
            <a-tag color="cyan" size="small">错误提示</a-tag>
            <span>: {{ viewingField.validation.message }}</span>
          </div>
          <div v-if="!hasValidationRules(viewingField)" class="no-validation">
            <a-empty description="该字段暂无验证规则" />
          </div>
        </div>
      </div>
    </a-modal>

    <!-- 验证规则编辑弹窗 -->
    <a-modal
      v-model:open="showEditModal"
      title="编辑验证规则"
      width="800px"
      @ok="handleSaveFieldValidation"
      @cancel="handleCancelFieldValidation"
    >
      <div v-if="editingField" class="field-validation-editor">
        <div class="field-basic-info">
          <h3>{{ editingField.fieldName }} ({{ editingField.fieldKey }})</h3>
          <a-tag :color="getFieldTypeColor(editingField.fieldType)">
            {{ editingField.fieldType }}
          </a-tag>
        </div>

        <a-divider />

        <a-form layout="vertical" :model="editingValidation">
          <!-- 基础验证 -->
          <div class="validation-group">
            <h4>
              <CheckCircleOutlined />
              基础验证
            </h4>
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item label="必填验证">
                  <a-switch
                    v-model:checked="editingValidation.required"
                    checked-children="必填"
                    un-checked-children="可选"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="错误提示信息">
                  <a-input
                    v-model:value="editingValidation.message"
                    placeholder="验证失败时的提示信息"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </div>

          <!-- 文本长度验证 -->
          <div v-if="isTextType(editingField.fieldType)" class="validation-group">
            <h4>
              <FontSizeOutlined />
              文本长度验证
            </h4>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="最小长度">
                  <a-input-number
                    v-model:value="editingValidation.minLength"
                    :min="0"
                    placeholder="最小字符数"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="最大长度">
                  <a-input-number
                    v-model:value="editingValidation.maxLength"
                    :min="0"
                    placeholder="最大字符数"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </div>

          <!-- 数值范围验证 -->
          <div v-if="isNumberType(editingField.fieldType)" class="validation-group">
            <h4>
              <NumberOutlined />
              数值范围验证
            </h4>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="最小值">
                  <a-input-number
                    v-model:value="editingValidation.min"
                    placeholder="最小数值"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="最大值">
                  <a-input-number
                    v-model:value="editingValidation.max"
                    placeholder="最大数值"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </div>

          <!-- 正则表达式验证 -->
          <div class="validation-group">
            <h4>
              <CodeOutlined />
              正则表达式验证
            </h4>
            <a-form-item label="正则表达式">
              <a-input
                v-model:value="editingValidation.pattern"
                placeholder="如: ^[0-9]+$ (只允许数字)"
              />
              <template #extra>
                <div class="pattern-templates">
                  <span class="template-label">常用模板：</span>
                  <a-space wrap>
                    <a-button
                      size="small"
                      type="link"
                      @click="applyPatternTemplate('^[0-9]+$')"
                    >
                      纯数字
                    </a-button>
                    <a-button
                      size="small"
                      type="link"
                      @click="applyPatternTemplate('^1[3-9]\\\\d{9}$')"
                    >
                      手机号
                    </a-button>
                    <a-button
                      size="small"
                      type="link"
                      @click="applyPatternTemplate('^\\\\S+@\\\\S+\\\\.\\\\S+$')"
                    >
                      邮箱
                    </a-button>
                    <a-button
                      size="small"
                      type="link"
                      @click="applyPatternTemplate('^[\\u4e00-\\u9fa5]+$')"
                    >
                      中文
                    </a-button>
                  </a-space>
                </div>
              </template>
            </a-form-item>

            <!-- 正则测试 -->
            <a-form-item
              v-if="editingValidation.pattern"
              label="正则测试"
            >
              <a-input
                v-model:value="patternTestValue"
                placeholder="输入测试文本"
                @input="testPattern"
              />
              <template #extra>
                <div class="test-result">
                  <a-tag
                    v-if="patternTestResult !== undefined"
                    :color="patternTestResult ? 'success' : 'error'"
                    size="small"
                  >
                    {{ patternTestResult ? '匹配成功' : '匹配失败' }}
                  </a-tag>
                </div>
              </template>
            </a-form-item>
          </div>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { message } from 'ant-design-vue'
import {
  SafetyCertificateOutlined,
  SaveOutlined,
  EditOutlined,
  EyeOutlined,
  DeleteOutlined,
  CheckCircleOutlined,
  FontSizeOutlined,
  NumberOutlined,
  CodeOutlined
} from '@ant-design/icons-vue'
import type {
  MerchantChannelConfig3,
  QRCodeConfig,
  ConfigField,
  FieldValidation
} from '@/types/protocol3-types'

// Props
interface Props {
  protocol?: MerchantChannelConfig3 | QRCodeConfig | null
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
})

// Emits
const emit = defineEmits<{
  save: [protocol: MerchantChannelConfig3 | QRCodeConfig]
  change: [protocol: MerchantChannelConfig3 | QRCodeConfig]
}>()

// 响应式数据
const saving = ref(false)
const showViewModal = ref(false)
const showEditModal = ref(false)
const viewingField = ref<ConfigField | null>(null)
const editingField = ref<ConfigField | null>(null)
const editingSectionIndex = ref(-1)
const editingFieldIndex = ref(-1)
const patternTestValue = ref('')
const patternTestResult = ref<boolean | undefined>(undefined)

// 编辑中的验证规则
const editingValidation = reactive<FieldValidation>({})

// 计算属性
const totalFieldsCount = computed(() => {
  if (!props.protocol?.configSections) return 0
  return props.protocol.configSections.reduce((count, section) => {
    return count + (section.fields?.length || 0)
  }, 0)
})

// 工具方法
const isTextType = (fieldType: string): boolean => {
  const textTypes = ['INPUT', 'PASSWORD', 'TEXTAREA', 'URL', 'EMAIL']
  return textTypes.includes(fieldType)
}

const isNumberType = (fieldType: string): boolean => {
  return fieldType === 'NUMBER'
}

const getFieldTypeColor = (fieldType: string): string => {
  const colorMap: Record<string, string> = {
    INPUT: 'blue', PASSWORD: 'red', TEXTAREA: 'cyan', SELECT: 'green',
    RADIO: 'orange', CHECKBOX: 'purple', SWITCH: 'geekblue',
    UPLOAD: 'volcano', URL: 'lime', EMAIL: 'gold', NUMBER: 'magenta'
  }
  return colorMap[fieldType] || 'default'
}

const getFieldTypeShortName = (fieldType: string): string => {
  const shortNames: Record<string, string> = {
    INPUT: '文本', PASSWORD: '密码', TEXTAREA: '多行', SELECT: '选择',
    RADIO: '单选', CHECKBOX: '多选', SWITCH: '开关',
    UPLOAD: '上传', URL: '链接', EMAIL: '邮箱', NUMBER: '数字'
  }
  return shortNames[fieldType] || fieldType
}

const hasValidationRules = (field: ConfigField): boolean => {
  if (!field.validation) return false
  return Object.keys(field.validation).some(key => {
    const value = field.validation![key as keyof FieldValidation]
    return value !== undefined && value !== null && value !== ''
  })
}

const getValidationRulesCount = (field: ConfigField): number => {
  if (!field.validation) return 0
  return Object.keys(field.validation).filter(key => {
    const value = field.validation![key as keyof FieldValidation]
    return value !== undefined && value !== null && value !== ''
  }).length
}

// 查看验证规则
const viewFieldValidation = (field: ConfigField) => {
  viewingField.value = field
  showViewModal.value = true
}

// 编辑验证规则
const editFieldValidation = (field: ConfigField, sectionIndex: number, fieldIndex: number) => {
  editingField.value = field
  editingSectionIndex.value = sectionIndex
  editingFieldIndex.value = fieldIndex

  // 复制当前验证规则到编辑对象
  Object.keys(editingValidation).forEach(key => {
    delete editingValidation[key as keyof FieldValidation]
  })

  if (field.validation) {
    Object.assign(editingValidation, field.validation)
  }

  // 重置测试数据
  patternTestValue.value = ''
  patternTestResult.value = undefined

  showEditModal.value = true
}

// 保存字段验证规则
const handleSaveFieldValidation = () => {
  if (!props.protocol?.configSections || editingSectionIndex.value === -1 || editingFieldIndex.value === -1) {
    return
  }

  const field = props.protocol.configSections[editingSectionIndex.value].fields[editingFieldIndex.value]

  // 清理空值
  const cleanValidation: any = {}
  Object.keys(editingValidation).forEach(key => {
    const value = editingValidation[key as keyof FieldValidation]
    if (value !== undefined && value !== null && value !== '') {
      cleanValidation[key] = value
    }
  })

  // 如果没有任何验证规则，删除validation属性
  if (Object.keys(cleanValidation).length === 0) {
    delete field.validation
  } else {
    field.validation = cleanValidation
  }

  emit('change', props.protocol)
  showEditModal.value = false
  message.success('验证规则已更新')
}

// 取消编辑
const handleCancelFieldValidation = () => {
  showEditModal.value = false
}

// 清除字段验证规则
const clearFieldValidation = (sectionIndex: number, fieldIndex: number) => {
  if (!props.protocol?.configSections) return

  const field = props.protocol.configSections[sectionIndex].fields[fieldIndex]
  delete field.validation

  emit('change', props.protocol)
  message.success('已清除字段验证规则')
}

// 应用正则表达式模板
const applyPatternTemplate = (pattern: string) => {
  editingValidation.pattern = pattern
  if (patternTestValue.value) {
    testPattern()
  }
  message.success('已应用正则表达式模板')
}

// 测试正则表达式
const testPattern = () => {
  if (!editingValidation.pattern || !patternTestValue.value) {
    patternTestResult.value = undefined
    return
  }

  try {
    const regex = new RegExp(editingValidation.pattern)
    patternTestResult.value = regex.test(patternTestValue.value)
  } catch (error) {
    patternTestResult.value = false
    message.warning('正则表达式格式错误')
  }
}

// 保存所有更改
const handleSave = async () => {
  if (!props.protocol) return

  saving.value = true
  try {
    emit('save', props.protocol)
    // 不在这里显示成功提示，由父组件处理API调用结果后显示
  } catch (error) {
    message.error('保存失败: ' + (error as Error).message)
  } finally {
    saving.value = false
  }
}
</script>

<style scoped>
.protocol-validations-simple-editor {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #e8e8e8;
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.protocol-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #666;
}

.field-count {
  margin-left: 8px;
}

.editor-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.loading-state, .empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
  background: white;
  border-radius: 8px;
}

.sections-container {
  /* Empty for now */
}

.section-card {
  margin-bottom: 16px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 参考add-or-edit的字段列表样式 */
.fields-list {
  /* Empty for now */
}

.field-item {
  margin-bottom: 8px;
  padding: 8px;
  background: #fafafa;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
}

.field-key {
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
}

/* 弹窗样式 */
.validation-details {
  padding: 16px 0;
}

.field-basic-info {
  margin-bottom: 16px;
}

.field-basic-info h3 {
  margin: 0 0 8px 0;
  color: #333;
}

.validation-rules-list {
  /* Empty for now */
}

.validation-rule {
  margin-bottom: 12px;
  padding: 8px 12px;
  background: #fafafa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.no-validation {
  text-align: center;
  padding: 32px;
}

.field-validation-editor {
  padding: 16px 0;
}

.validation-group {
  margin-bottom: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.validation-group h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
}

.pattern-templates {
  margin-top: 8px;
  padding: 8px;
  background: #f0f2f5;
  border-radius: 4px;
}

.template-label {
  font-size: 12px;
  color: #666;
  margin-right: 8px;
}

.test-result {
  margin-top: 8px;
}
</style>